import json
import time
from websocket.redis_ws import r_ws


def bytes_to_object(byte):
    # s = byte.decode()
    result = eval(byte)
    return result


class MessageType:
    SOCKET_HEART = "socketHeart"
    CONTROL_DEVICE = "control_device"
    GET_DEVICE_LIST = "get_device_list"


class Ws:
    def __init__(self,  sock, router_mac):
        self.sock = sock
        self.router_mac = router_mac

    def run_forever(self):
        while True:
            message = self.sock.receive()
            # print('websocket receive '+ message)
            if message is not None:
                print('websocket receive ' + message)
                message = bytes_to_object(message)
                self.process_message(message)
                # print(self.messages)
            else:
                return

    def process_message(self, message):
        if message["destination"] is MessageType.SOCKET_HEART:
            print('websocket receive socketHeart')
            return
        if message["action"] is MessageType.CONTROL_DEVICE:
            print(message["action"], json.dumps(message))
            print('gateWayDeviceId:' + message["gateWayDeviceId"])
            # r_ws.set(self.router_mac + ":" + message["action"], json.dumps(message))
            return
        if message["action"] is MessageType.GET_DEVICE_LIST:
            print(message["action"], json.dumps(message))
            print('gateWayDeviceId:' + message["gateWayDeviceId"])
            data = message["data"]
            for key in range(len(data)):
                print("deviceType:" + data[key]["deviceType"])
                print("deviceName:" + data[key]["deviceName"])
                print("endpoint_id:" + data[key]["endpoint_id"])
                print("deviceAddress:" + data[key]["deviceAddress"])

            r_ws.set(self.router_mac + ":" + message["action"], json.dumps(message))  # 将数据存入redis数据库
            return
        else:
            print(self.router_mac + ":" + message["action"], json.dumps(message))
            return

    def send(self, message):
        self.sock.send(message)

    def get_reply(self, message_type):
        # for i in range(120):
        #     time.sleep(0.1)
        reply = r_ws.get(self.router_mac + ":" + message_type)
            #print(i)
            #reply = r_ws.hget(self.router_mac, message_type)
            #r_ws.r.delete(self.router_mac + ":" + message_type)
        if reply is not None:
            return json.loads(reply)
        return None
